<template>

  <div>
    <!--     v-loading="hasRelateListLoading"  -->
    <azure-dynamic-table
      :column-des-objs="columnDesObjs"
      :data="tableData"
      :empty-text="`该暂${linkFrom}暂无配置的${linkTo} 🎉🎉🎉🎉🎉`"
      :showSeq="true"
    >
      <template slot="tableHead">
        <AButton @click="handleConfigRelate" type="success">
          {{`配置当前${linkFrom}的${linkTo}`}}
        </AButton>
        <!--        <AButton @click="saveRelate2Server" type="primary">-->
        <!--          {{`保存${linkFrom}与所属${linkTo}`}}-->
        <!--        </AButton>-->
        <!--          <el-input clearable placeholder="请输入内容"-->
        <!--                    style="width: 200px;margin-right: 20px" suffix-icon="el-icon-search"-->
        <!--                    v-model="searchKey"/>-->
        <!--        <ASelect :options="PRODUCT_SYNC_STATUS" :value.sync="putAway" placeholder="选择产品同步状态"/>-->
      </template>

      <template slot="operator" slot-scope="{scope:{row,$index}}">
        <AButton @click="handleEdit({row,$index})" type="primary">编辑{{linkTo}}</AButton>
        <el-popconfirm
          :title="`是否确定删除${linkFrom}下的该${linkTo}？`"
          @confirm="handleDeleteProduct({row,$index})"
          style="margin-left: 10px;">
          <!--          <AButton slot="reference" type="info">-->
          <!--            删除-->
          <!--          </AButton>-->
        </el-popconfirm>
      </template>
    </azure-dynamic-table>

    <!--        @checkedItemListChange="(payload)=>$emit('checkedItemListChange',payload)"  -->
    <!--  配置 (p -> c , t -> p) 关系 drawer  -->
    <show-all-product-list
      :checkedItemIds="proxyCheckedItemIds"
      :modifyData="modifyData"
      :submitBeforeCallback="submitModify"
      :tableData.sync="proxyTableData"
      ref="allProductList"/>
  </div>

</template>

<script>
  import { createProductFactory, productBaseCols } from '@/views/baseproduct/mixins/productUtil'
  import ShowAllProductList from '@/views/baseproduct/components/product/ShowAllProductListDrawer'
  import AButton from '@/components/ATheFridayClub/AButton'
  import AzureDynamicTable from '@/components/ATheFridayClub/mDynamicTable/AzureDynamicTable'
  import Sticky from '@/components/Sticky/index'
  import { ModifyProductComponent, PageQueryProduct, QueryProductComponent } from '@/api/productInformation'
  import { ERR_OK } from '@/utils/commons'
  import { productTypesEnum } from '@/enums/product'
  import layoutMixin from '@/mixins/layoutMixin'
  import productMixin from '@/views/baseproduct/components/product/productMixin'
  import { objFirstKeyLowerCase } from '@/utils/fridayClub/objectUtil'
  import { debugLogger } from '@/utils/fridayClub/functianal'
  import { dataStatusTypesEnum } from '@/enums/common'

  const columnDesObjs = Array.of(
    ...productBaseCols,
    { key: 'operator', label: '操作', width: '120' }
  )

  export default {
    name: 'ProductRelateConfig',
    props: {
      tableData: {
        type: Array,
        default: () => ([])
      },
      modifyData: { //  因为修改配置信息要用
        type: Object,
        default: () => ({})
      }
    },
    computed: {
      proxyTableData: {
        get() {
          return this.tableData
        },
        set(newTableData) {
          this.$emit('tableDataUpdate', newTableData)
        }
      },
      proxyCheckedItemIds: {
        get() {
          // return this.tableData.map(v => v.ProductId)
          return this.tableData.map(v => v.partId)
        }
      },
      isProductEdit() {
        //  当前编辑的不为产品就不然进入
        if (this.proxyProductType !== productTypesEnum['产品']) {
          return this.$message.info('当前只能配置产品与组件关联关系')
        }
      }
    },
    mixins: [productMixin],
    components: { ShowAllProductList, AButton, AzureDynamicTable, Sticky },
    data() {
      return {
        columnDesObjs

      }
    },
    methods: {

      // handleCheckedItemIdsChange({ retTableData, checkedItems, checkedIds }) {
      //   // this.$emit('changeTableData', retTableData)
      //   this.proxyTableData = retTableData
      // },
      handleConfigRelate() {
        // this.$emit('configRelate')

        this.$refs['allProductList'].show()
      },

      saveRelate2Server() {

      },

      //  删除关系 ????? 考虑到底要不要
      handleDeleteProduct() {
        //  派发事件直接更新整个tableData

      },

      //  删除,新增 调用  { status } = {}
      async submitModify({ resolve, reject, deleteItems }) {
        try {
          const { tableData } = this
          const { ProductId } = this.modifyData  //  大写
          if (ProductId <= 0) {
            return this.$message.info(`请先创建产品基本信息.`)
          }
          const modifyDatas = tableData
            // .map(c => c |>  objFirstKeyLowerCase)
            .map((cur) => {
              const { componentId, partId, productId, quantity, status } = cur
              // console.log(componentId, partId, productId, quantity, status)
              return ({ componentId, partId, productId, quantity, status })
            })
            .map(c => {
              const { componentId, partId, productId } = c
              if (!componentId) {
                return {   //  工厂
                  partId, //  设置产品下组件的id
                  productId: ProductId, //  设置主产品的id
                  quantity: 1,
                  status: dataStatusTypesEnum['正常']
                }
              }
              return c
            })
          //  和原始的进行比较
          const { Code } = await ModifyProductComponent(modifyDatas.concat(
            deleteItems.map((c) => {
              const { partId, productId, quantity, status } = c
              return { partId, productId, quantity, status: dataStatusTypesEnum['删除'] }
            })))
          if (Code === ERR_OK) {
            resolve()
            this.$message.success(`配置${this.linkFrom}的${this.linkTo}成功`)
          } else {
            reject()
          }
        } catch (e) {
          console.log(e)
          reject()
        }
      },

      //  组件不能新增只能修改
      handleEdit({ row, $index }) {
        // console.log(productTypesEnum['产品'])
        // console.log(this.proxyProductType)

        const { ProductId, Code, partId } = row
        this.$router.push({ name: 'componentModify', query: { ProductId: partId, Code } })
      }

    }

  }
</script>

<style lang="scss" scoped>

</style>
